package 并发编程18.自旋锁;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 不可重入的自旋锁
 *
 * @author idea
 * @data 2019/2/19
 */
public class SpinLock {

    private AtomicReference<Thread> cas = new AtomicReference<>();

    public void lock() {
        Thread current = Thread.currentThread();
        //如果没有cas成功就会进入自旋
        //这样子会有个缺陷，一直循环，导致线程肌饿
        //优点：线程一直都是running状态，减少了线程之间的状态切换
        while (!cas.compareAndSet(null, current)) {

        }
    }

    public void unlock() {
        //获取成功之后就会解锁
        Thread current = Thread.currentThread();
        cas.compareAndSet(current, null);
    }

}
